<template>
  <div class="json-editor">
    <el-input
      v-model="content"
      type="textarea"
      :rows="rows"
      :placeholder="placeholder"
      @input="handleInput"
      @blur="formatJson"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps<{
  modelValue: string
  height?: string
  placeholder?: string
}>()

const emit = defineEmits(['update:modelValue'])

// 计算行数
const rows = computed(() => {
  const height = parseInt(props.height || '300px')
  return Math.floor(height / 21) // 假设每行大约 21px
})

// 内部内容
const content = ref(props.modelValue)

// 监听外部值变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== content.value) {
    content.value = formatJsonString(newValue)
  }
})

// 处理输入
const handleInput = (value: string) => {
  content.value = value
  emit('update:modelValue', value)
}

// 格式化 JSON
const formatJson = () => {
  try {
    content.value = formatJsonString(content.value)
    emit('update:modelValue', content.value)
  } catch (error) {
    // 如果不是有效的 JSON，保持原样
  }
}

// JSON 格式化函数
const formatJsonString = (json: string): string => {
  try {
    const obj = JSON.parse(json)
    return JSON.stringify(obj, null, 2)
  } catch {
    return json
  }
}

// 初始化时尝试格式化
if (props.modelValue) {
  content.value = formatJsonString(props.modelValue)
}
</script>

<style scoped>
.json-editor {
  width: 100%;
}

:deep(.el-textarea__inner) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 14px;
  line-height: 1.5;
  padding: 8px;
}

.dark {
  :deep(.el-textarea__inner) {
    background-color: #1e1e1e;
    color: #d4d4d4;
    border-color: #4c4d4f;
  }
}
</style> 